package cn.cmcc.online.smsapi.sdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.log.LogManager;

public class MD5FileUtil {

	public static String getFileMD5String(File file) throws IOException {

		MessageDigest md5 = null;
		FileInputStream in = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			FileChannel ch = in.getChannel();
			MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY,
					0, file.length());
			md5.update(byteBuffer);
			return bufferToHex(md5.digest());
		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
            LogManager.e(Constant.TAG, "getFileMD5String: ", e);

		}catch (Throwable e) {
//			e.printStackTrace();
            LogManager.e(Constant.TAG, "getFileMD5String: ", e);

		}finally{
			FileUtils.close(in);
		}
		return null;

	}

	public static String bufferToHex(byte[] bytes) {
		if (bytes == null)
			return null;
		String table = "0123456789abcdef";
		int len = 2 * bytes.length;
		char[] cchars = new char[len];
		for (int i = 0, k = 0; i < bytes.length; i++, k++) {
			int b;
			b = 0x0f & (bytes[i] >> 4);
			cchars[k] = table.charAt(b);
			b = 0x0f & bytes[i];
			k++;
			cchars[k] = table.charAt(b);
		}
		String sret = String.valueOf(cchars);
		cchars = null;
		return sret;
	}

}